<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="orderList" border>
      <el-table-column label="订单ID" align="center" prop="ID" min-width="150" show-overflow-tooltip />
      <el-table-column label="用户ID" prop="UserID" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.UserID || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺ID" prop="ShopID" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.ShopID || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" prop="Type" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ getOrderTypeLabel(scope.row.Type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品信息" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="scope.row.Goods && scope.row.Goods.length > 0">
            <div v-for="(item, index) in scope.row.Goods" :key="index" class="goods-item">
              <span>{{ item.Snapshot ? item.Snapshot.name : '-' }}</span>
              <span class="goods-quantity">x{{ item.Quantity || 1 }}</span>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" width="120" align="center">
        <template slot-scope="scope">
          <span>¥{{ calculateOrderTotal(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" prop="PayType" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ getPayTypeLabel(scope.row.PayType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否配送" prop="IsDelivery" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.IsDelivery ? 'success' : 'info'">
            {{ scope.row.IsDelivery ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="Status" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getOrderStatusTagType(scope.row)">{{ getOrderStatusLabel(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.PayTime ? parseTime(scope.row.PayTime) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="CreatedAt" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.CreatedAt ? parseTime(scope.row.CreatedAt) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="UpdatedAt" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.UpdatedAt ? parseTime(scope.row.UpdatedAt) : '-' }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import { getOrderList } from '@/api/api'

export default {
  name: 'Order',
  data() {
    return {
      loading: false,
      showSearch: true,
      orderList: [],
      total: 0,
      queryParams: {
        page: 1,
        pageSize: 10
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      getOrderList(this.queryParams)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.orderList = list
          this.total = total || list.length
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    formatPrice(price) {
      if (price === undefined || price === null || price === '') {
        return '0.00'
      }
      return Number(price).toFixed(2)
    },
    calculateOrderTotal(order) {
      // 计算订单总金额：遍历 Goods 数组，计算 Quantity * Snapshot.price 的总和
      if (!order.Goods || !Array.isArray(order.Goods) || order.Goods.length === 0) {
        return '0.00'
      }
      let total = 0
      order.Goods.forEach(item => {
        const quantity = item.Quantity || 0
        const price = item.Snapshot && item.Snapshot.price ? Number(item.Snapshot.price) : 0
        total += quantity * price
      })
      return this.formatPrice(total)
    },
    getOrderStatusLabel(order) {
      // 如果订单 Type === 2（家政服务）且订单 Status === 2（已支付），则显示商品状态；否则显示订单状态
      if (order.Type === 2 && order.Status === 2 && order.Goods && order.Goods.length > 0) {
        const goodsStatus = order.Goods[0].Status
        return this.getGoodsStatusLabel(goodsStatus)
      }
      return this.getOrderStatusLabelByValue(order.Status)
    },
    getOrderStatusTagType(order) {
      // 如果订单 Type === 2（家政服务）且订单 Status === 2（已支付），则返回商品状态的标签类型；否则返回订单状态的标签类型
      if (order.Type === 2 && order.Status === 2 && order.Goods && order.Goods.length > 0) {
        const goodsStatus = order.Goods[0].Status
        return this.getGoodsStatusTagType(goodsStatus)
      }
      return this.getOrderStatusTagTypeByValue(order.Status)
    },
    getOrderStatusLabelByValue(value) {
      // 订单状态映射（根据后端定义）
      const statusMap = {
        0: '未知',
        1: '待支付',
        2: '已支付',
        3: '已完成',
        4: '已取消',
        5: '已退款',
        6: '退款中',
        7: '部分退款',
        8: '已过期',
        9: '退款失败'
      }
      return statusMap[value] || '未知'
    },
    getGoodsStatusLabel(value) {
      // 商品状态映射（根据后端定义）
      const statusMap = {
        1: '待分配',
        2: '待服务',
        3: '正在服务',
        4: '已完成',
        5: '待取货',
        6: '待确认'
      }
      return statusMap[value] || '未知'
    },
    getOrderStatusTagTypeByValue(value) {
      // 根据订单状态返回对应的标签类型
      const typeMap = {
        0: 'info',      // 未知
        1: 'warning',   // 待支付
        2: 'success',   // 已支付
        3: 'success',   // 已完成
        4: 'danger',    // 已取消
        5: 'info',      // 已退款
        6: 'warning',   // 退款中
        7: 'info',      // 部分退款
        8: 'info',      // 已过期
        9: 'danger'     // 退款失败
      }
      return typeMap[value] || 'info'
    },
    getGoodsStatusTagType(value) {
      // 根据商品状态返回对应的标签类型
      const typeMap = {
        1: 'warning',   // 待分配
        2: 'warning',   // 待服务
        3: 'info',      // 正在服务
        4: 'success',   // 已完成
        5: 'warning',   // 待取货
        6: 'warning'    // 待确认
      }
      return typeMap[value] || 'info'
    },
    getOrderTypeLabel(value) {
      // 订单类型映射
      const typeMap = {
        1: '普通商品',
        2: '家政服务',
        3: '公益服务',
        4: '食堂饭卡',
        5: '套餐权益'
      }
      return typeMap[value] || '-'
    },
    getPayTypeLabel(value) {
      // 支付方式映射
      const payTypeMap = {
        0: '未支付',
        1: '微信支付',
        2: '支付宝',
        3: '现金',
        4: '其他'
      }
      return payTypeMap[value] || '-'
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .goods-quantity {
    color: #909399;
    font-size: 12px;
    margin-left: 8px;
  }
}
</style>

